

<template>
  <div>
    <div class="goodsImgList-mokuai">
      <!-- 数据模块 -->
      <div class="goodsImgList-index">
        <div class="goodsImgList-index-top">
          <div class="goodsImgList-name">
            <div class="goodsImgList-name-font">
              <i class="el-icon-s-unfold"></i>
              数据列表
            </div>
            <div class="goodsImgList-index-select">
              <div class="goodsImgList-left goodsImgList-index-select-button">
                <el-button @click="onSubmitImg" size="small">上传图片</el-button>
              </div>
              <div class="goodsImgList-left">
                <el-form :inline="true" :model="listLine" class="demo-form-inline" size="small">
                  <!--<el-form-item label="">-->
                  <!--<el-select v-model="listLine.row" placeholder="显示条数" class="select-width-2">-->
                  <!--<el-option label="10条" value="10"></el-option>-->
                  <!--<el-option label="20条" value="20"></el-option>-->
                  <!--<el-option label="30条" value="30"></el-option>-->
                  <!--</el-select>-->
                  <!--</el-form-item>-->
                  <el-form-item label>
                    <el-select v-model="listLine.sort" placeholder="排序方式" class="select-width-2">
                      <el-option label="默认" value="0"></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </div>
              <div class="goodsImgList-left goodsImgList-index-select-button">
                <el-button icon="el-icon-arrow-left" @click.native="returnButton" size="small">返回</el-button>
              </div>
            </div>
          </div>
          <div class="goodsImgList-content">
            <!-- 数据列表 -->
            <div>
              <!-- 一张图片 -->
              <div class="img-div" v-for="fit in fits" v-if="fit!=''" :key="fit">
                <div class="demo-image">
                  <div class="block img-array">
                    <el-image style="width:140px; height:140px" :src="requestUrl+fit" :fit="fit"></el-image>
                  </div>
                </div>
                <div class="img-div-button">
                  <el-button type="text" @click="shiftAlbum(fit)">转移相册</el-button>
                  <el-button type="text" @click="deleteImgs(fit)">删除图片</el-button>
                </div>
              </div>
            </div>
            <!-- 页脚 -->
            <div class="goodsImgList-paging">
              <!-- 批量操作 -->
              <div class="goodsImgList-paging-leftlayout">
                <div class="opertation-block">
                  <!-- 全选需要设置方法目前只能操作0，1数据 -->
                  <el-button @click="toggleSelection([tableData[0], tableData[1]])" size="small">全选</el-button>
                </div>
                <div class="opertation-block">
                  <el-form :inline="false" :model="operation" class="demo-form-inline" size="small">
                    <el-form-item label>
                      <el-select
                        v-model="operation.opertationType"
                        placeholder="批量操作"
                        class="select-width-2"
                      >
                        <el-option label="删除" value="0"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-form>
                </div>
                <div class="opertation-block">
                  <el-button size="small">确定</el-button>
                </div>
              </div>
              <!-- 分页 -->
              <div class="goodsImgList-paging-layout">
                <div class="block">
                  <span class="demonstration"></span>
                  <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage4"
                    layout="total, prev, pager, next, jumper"
                    :total="total"
                  ></el-pagination>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 弹出框 -->
    <div>
      <el-drawer
        title="上传图片"
        :before-close="handleClose"
        :visible.sync="dialog"
        direction="ttb"
        custom-class="demo-drawer"
        ref="drawer"
        class="custom-class"
        size="70%"
      >
        <div class="demo-drawer__content">
          <el-form :model="form">
            <el-form-item label="选择相册" :label-width="formLabelWidth">
              <el-select v-model="form.imgAlbum" placeholder="请选择相册">
                <el-option v-for="item1 in items" :label="item1.title" :value="item1.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="选择图片" :label-width="formLabelWidth">
              <el-upload
                class="upload-demo"
                ref="upload"
                action="https://jsonplaceholder.typicode.com/posts/"
                :file-list="fileList"
                :before-upload="beforeAvatarUpload"
                list-type="picture"
                :http-request="modeUpload"
                :on-success="handleAvatarSuccess"
                :on-change="handleChange"
              >
                <el-button class="upload-width" size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </el-form-item>
          </el-form>
          <div class="demo-drawer__footer form-button-center">
            <el-button @click="cancelForm">取 消</el-button>
            <el-button
              type="primary"
              @click="addImg"
              :loading="loading"
            >{{ loading ? '提交中 ...' : '确 定' }}</el-button>
          </div>
        </div>
      </el-drawer>
    </div>
    <!-- 弹出框2 -->
    <div>
      <el-drawer
        title="上传图片"
        :before-close="handleCloseTwo"
        :visible.sync="shiftForm"
        direction="ttb"
        custom-class="demo-drawer"
        ref="drawer"
        class="custom-class"
        size="30%"
      >
        <div class="demo-drawer__content">
          <el-form :model="formTwo">
            <el-form-item label="选择相册" :label-width="formLabelWidthTwo">
              <el-select v-model="formTwo.imgAlbum" placeholder="选择转移相册">
                <el-option v-for="item1 in items" :label="item1.title" :value="item1.id"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div class="demo-drawer__footer form-button-center">
            <el-button @click="cancelFormTwo">取 消</el-button>
            <el-button
              type="primary"
              @click="moveImg"
              :loading="loadingTwo"
            >{{ loadingTwo ? '提交中 ...' : '确 定' }}</el-button>
          </div>
        </div>
      </el-drawer>
    </div>
  </div>
</template>


<style>
/* 自定义 */
.form-button-center {
  margin-left: 110px;
}
.select-width-2 {
  width: 100px;
}
.goodsImgList-left {
  float: right;
}
.goodsImgList-mokuai {
  height: 1000px;
  background-color: rgb(249, 249, 249);
}
.goodsImgList-index {
  width: 100%;
  margin: auto;
  background-color: rgb(255, 255, 255);
}
.goodsImgList-index-top {
  margin-top: 30px;
}
.goodsImgList-name {
  width: 100%;
  height: 50px;
  padding-top: 10px;
  background-color: rgb(240, 240, 240);
}
.goodsImgList-name-font {
  height: 40px;
  line-height: 40px;
  float: left;
  margin-left: 20px;
  font-size: 14px;
}

.goodsImgList-index-select {
  width: 430px;
  float: right;
  margin-right: 20px;
  font-size: 14px;
  padding-top: 5px;
}
.goodsImgList-index-select-button {
  margin-right: 20px;
}
.goodsImgList-content {
  width: 100%;
  padding-top: 40px;
}
.goodsImgList-button-select-2 {
  height: 50px;
  padding-top: 10px;
  padding-left: 20px;
}

.opertation-block {
  display: inline-block;
  margin-left: 3px;
}
.goodsImgList-paging {
  height: 50px;
  width: 100%;
  background-color: rgb(253, 253, 254);
}
.goodsImgList-paging-leftlayout {
  float: left;
  margin-top: 7px;
}
.goodsImgList-paging-layout {
  float: right;
  margin-top: 7px;
}
.custom-class {
  width: 30%;
  margin: auto;
}
.img-div {
  margin-top: 10px;
  width: 150px;
  display: inline-block;

  margin-left: 2%;
}
.img-div-button {
  width: 140px;
  margin: auto;
  height: 40px;
  background-color: rgb(240, 240, 240);
  text-align: center;
}
.demo-image {
  height: auto !important;
}
</style>

<script>
import goodImgeListApi from "@/api/goods/imagelist";
export default {
  data() {
    return {
      requestUrl: goodImgeListApi.getRequestUrl().defaults.baseURL + "/api-goods/album/",
      total: 0,

      // 筛选
      listLine: {
        row: "30",
        sort: "0"
      },
      items: [],
      operation: {
        opertationType: "0"
      },
      // 分页
      currentPage4: 1,
      // 弹出框
      dialog: false,
      loading: false,
      form: {
        name: "",
        imgAlbum: "",
        fileList: []
      },
      formLabelWidth: "80px",
      timer: null,
      // 弹出框2
      shiftForm: false,
      loadingTwo: false,
      formTwo: {
        imgAlbum: ""
      },
      formLabelWidthTwo: "80px",
      timerTwo: null,
      mode: "",
      imageUrl: "",
      parentId33: this.$route.query.parentId,
      imgPath: "",
      selectedCheck: [],
      // 图片
      fits: [],
      // 图片地址手动添加
      imgUrl:
        "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"
    };
  },
  methods: {
    // 返回
    returnButton() {
      this.$router.replace({ path: "/goods/goodsImage" });
    },
    // 数据列表
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },

    modeUpload: function(item) {
      this.mode = item.file;
    },

    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 < 500;

      if (!isJPG) {
        this.$message.error("封面只能是 JPG和png 格式!");
      }
      if (!isLt2M) {
        this.$message.error("封面大小不能超过 500kb!");
      }
      return isJPG && isLt2M;
    },
    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    },

    // 弹出框
    onSubmitImg() {
      this.dialog = true;
    },
    shiftAlbum(imgUrl) {
      this.shiftForm = true;
      this.imgPath = imgUrl;
    },
    deleteImgs(imgId) {
      this.$confirm("是否确定删除？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let param = new FormData(); //创建form对象
        param.append("imgs", imgId);
        console.info(this.parentId33);
        param.append("id", this.parentId33);
        this.axios
          .post(this.requestUrl + "deleteImg?token=11", param)
          .then(response => {
            if (response.data.code == 200) {
              this.$message({
                type: "success",
                message: "删除成功！"
              });

              this.initImg();
            } else {
              this.$message({
                type: "error",
                message: response.data.msg
              });
            }
          });
      });
    },
    // 处理图片
    handleChange(file, fileList) {
      // this.fileList = fileList.slice(-3);
    },
    // 弹出框处理
    handleClose(done) {
      this.cancelForm();
      this.cancelFormTwo();
      // if (this.loading) {
      //   return;
      // }
      // this.$confirm('确定要提交表单吗？')
      //   .then(_ => {
      //     this.loading = true;
      //     this.timer = setTimeout(() => {
      //       done();
      //       // 动画关闭需要一定的时间
      //       setTimeout(() => {
      //         this.loading = false;
      //       }, 400);
      //     }, 2000);
      //   })
      //   .catch(_ => {});
    },
    cancelForm() {
      this.loading = false;
      this.dialog = false;
      clearTimeout(this.timer);
    },
    // 弹出框2处理
    handleCloseTwo(done) {
      this.cancelForm();
      this.cancelFormTwo();
      // if (this.loadingTwo) {
      //   return;
      // }
      // this.$confirm('确定要提交表单吗？')
      //   .then(_ => {
      //     this.loadingTwo = true;
      //     this.timerTwo = setTimeout(() => {
      //       done();
      //       // 动画关闭需要一定的时间
      //       setTimeout(() => {
      //         this.loadingTwo = false;
      //       }, 400);
      //     }, 2000);
      //   })
      //   .catch(_ => {});
    },
    cancelFormTwo() {
      this.loadingTwo = false;
      this.shiftForm = false;
      clearTimeout(this.timerTwo);
    },
    initImg() {
      let param = new FormData(); //创建form对象
      param.append("id", this.parentId33);
      this.axios
        .post(this.requestUrl + "findById?token=11", param)
        .then(response => {
          if (response.data.code == 200) {
            if (response.data.msg != "") {
              this.fits = response.data.msg.split(",");
              this.total = this.fits.length - 1;
            } else {
              this.total = 0;
              this.fits = [];
            }
          }
        });
    },
    moveImg() {
      if (this.formTwo.imgAlbum == "") {
        this.$message.warning("请选择相册!");
        return;
      }

      let param = new FormData(); //创建form对象
      param.append("id", this.formTwo.imgAlbum);
      param.append("imgPath", this.imgPath);
      this.axios
        .post(this.requestUrl + "updateImg?token=11", param)
        .then(response => {
          if (response.data.code == 200) {
            this.cancelFormTwo();
            this.$message({
              type: "success",
              message: "转移成功！"
            });
            this.initImg();
            this.formTwo.imgAlbum = "";
          } else {
            this.$message({
              type: "error",
              message: response.data.msg
            });
          }
        });
    },
    addImg() {
      if (this.form.imgAlbum == "") {
        this.$message.warning("请选择相册!");
        return;
      }
      if (this.mode == "") {
        this.$message.warning("请选择图片!");
        return;
      }

      let param = new FormData(); //创建form对象
      param.append("file", this.mode);
      param.append("id", this.form.imgAlbum);

      let config = {
        headers: { "Content-Type": "multipart/form-data" } //这里是重点，需要和后台沟通好请求头，Content-Type不一定是这个值
      };
      this.axios
        .post(this.requestUrl + "uploadImg?token=11", param, config)
        .then(response => {
          if (response.data.code == 200) {
            this.cancelForm();
            this.$message({
              type: "success",
              message: "上传成功！"
            });
            this.initImg();
            this.mode = "";
            this.form.imgAlbum = "";
            this.fileList = [];
          } else {
            this.$message({
              type: "error",
              message: response.data.msg
            });
          }
        });
    },
    initData() {
      if (
        this.$route.query.imageItems != undefined &&
        this.$route.query.imageItems != ""
      ) {
        console.info(this.$route.query.imageItems);
        var imgss = this.$route.query.imageItems;
        this.fits = imgss.split(",");
        this.total = this.fits.length - 1;
        this.initImg();
      }
      this.axios
        .get(this.requestUrl + "findAll?token=11&test=")
        .then(response => {
          if (response.data.code == 200) {
            this.items = response.data.msg;
          }
        });
    }
  },
  mounted() {
    this.initData();
    this.initImg();
  }
};
</script>